package com.itshizhan.itjidancideveloper.controller.ucenter

import com.itshizhan.itjidancideveloper.dao.ucenter.ArticleDao
import com.itshizhan.itjidancideveloper.models.Article
import com.itshizhan.itjidancideveloper.models.ucenter.ArticleQuery
import com.itshizhan.itjidancideveloper.response.Response
import org.springframework.data.domain.Page
import org.springframework.data.domain.PageRequest
import org.springframework.data.jpa.domain.Specification
import org.springframework.web.bind.annotation.*
import java.util.*


@RestController()
@RequestMapping("/ucenter/article")
class ArticleController(private var articleDao: ArticleDao) {

  @PostMapping("/list")
  fun getList(@RequestParam("pageIndex") pageIndex: Int,
              @RequestParam("pageSize") pageSize: Int,
              @RequestBody() articleQuery: ArticleQuery
  ): Response<Page<Article>> {
    //注意：从第0页开始的
    val pageable = PageRequest.of(pageIndex-1,pageSize)
    val spec = Specification<Article> { root, query, cBuilder ->
      /**模糊查询**/
      val likeCondition = cBuilder.like(root.get("title"), "%"+articleQuery.title+"%")
      val stateCondition = cBuilder.equal(root.get<String>("state"),articleQuery.state)
      query.where(likeCondition,stateCondition)
      return@Specification null
    }
    val pageArticle = articleDao.findAll(spec, pageable)
    return Response.success(pageArticle)
  }

  @GetMapping("/detail")
  fun getDetailById(@RequestParam("id") id: Int): Response<Optional<Article>> {
    val article = articleDao.findById(id)
    return Response.success(article)
  }

  @PostMapping("/save")
  fun save(@RequestBody() article: Article): Response<Article> {
    val articleId = article.id;
    println("articleId = [${articleId}]")
    if(articleId==0){
     //新增
      val articleDb = articleDao.save(article)
      return Response.success(articleDb)
    }else {
      //修改
      val dbArticle = articleDao.findById(articleId).orElse(null)
      println("dbArticle==$dbArticle")
      return if (dbArticle!=null) {
        dbArticle.title = article.title
        dbArticle.contentMd = article.contentMd
        dbArticle.contentHtml = article.contentHtml
        val saveArticle = articleDao.save(dbArticle)
        Response.success(saveArticle)
      }else {
        Response.fail()
      }
    }
  }

}